import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:ride_rex/coin_shop/coin_shop_bean.dart';
import 'package:ride_rex/coin_shop/coin_shop_logic.dart';
import 'package:ride_rex/generated/assets.dart';
import 'package:ride_rex/service/user_service.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../service/log_service.dart';

class CoinShopPage extends GetView<CoinShopLogic> {
  const CoinShopPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      titleStr: 'Coin Shop',
      titleColor: Colors.white,
      appbarBackgroundColor: '#9AE7FF'.toColor,
      backIcon: Assets.svgAppbarBack,
      backColor: Colors.white,
      // actions: [
      //   CommonRootAction(
      //     child: const IconWidget.image(Assets.pngIapCustomer, size: 30),
      //     onTap: () {
      //       if (controller.customerId.empty) return;
      //       LMLogManager.stat(page: 'customer');
      //     },
      //   )
      // ],
      child: GetBuilder<CoinShopLogic>(
        init: CoinShopLogic(),
        builder: (logic) {
          return SingleChildScrollView(
            child: Column(
              children: [
                _buildTop().padding(left: 16.w, right: 16.w, top: 18.w),
                _buildItemWrap().padding(left: 16.w, right: 16.w, top: 18.w),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildTop() => AspectRatio(
        aspectRatio: 2.71,
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(Assets.pngIapBg),
              fit: BoxFit.cover,
            ),
          ),
          child: Row(
            children: [
              IconWidget.image(Assets.pngIapCoin, width: 106.w, height: 82.w).paddingLeft(12.w),
              Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextWidget.oneLine(text: 'My Coins', fontSize: 16, color: '#1B614E'.toColor),
                  ValueListenableBuilder(
                    valueListenable: UserService.instance.notifierOfMineInfo,
                    builder: (BuildContext context, MineInfoBean value, Widget? child) {
                      return TextWidget.oneLine(
                        text: (value.availableCoins ?? 0).toString(),
                        fontSize: 26,
                        color: '#1B614E'.toColor,
                        fontWeight: FontWeight.bold,
                      ).paddingTop(5.w);
                    },
                  ),
                ],
              ).paddingLeft(16.w),
            ],
          ),
        ),
      );

  Widget _buildItemWrap() {
    return LayoutBuilder(
      builder: (context, constraints) {
        double width = constraints.maxWidth;
        double spacing = 11.w;
        double itemWidth = ((width - spacing) / 2).floorToDouble();
        return Wrap(
          spacing: spacing,
          runSpacing: 16.w,
          children: List.generate(
            controller.goodsList.length,
            (index) => RechargeItem(
              controller.goodsList[index],
              itemWidth,
              onTap: () => controller.createOrder(controller.goodsList[index]),
            ),
          ).toList(),
        );
      },
    );
  }
}

class RechargeItem extends StatelessWidget {
  RechargeItem(this.bean, this.width, {super.key, this.onTap});

  final double width;
  late final bool isHot = bean.tags.equals('Hot');
  final GoodsBean bean;
  final VoidCallback? onTap;

  @override
  Widget build(BuildContext context) {
    return ButtonWidget(
      hasInkWell: false,
      onTap: onTap,
      child: Stack(
        alignment: Alignment.topRight,
        children: [
          Container(
            width: width,
            decoration: CommonDecoration.getShapeDecoration(
              bg: Colors.white,
              radius: 8.w,
              borderWidth: 2.w,
              borderColor: Colors.white,
            ),
            child: AspectRatio(
              aspectRatio: 2.24,
              child: Column(
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      _buildCoin().paddingLeft(8.w),
                      _buildCoinNum().paddingLeft(8.w).flexible(),
                      _buildDiscount().padding(left: 3.w, bottom: 4.w),
                    ],
                  ).paddingBottom(6.w).expanded(),
                  Container(
                    height: 22.w,
                    decoration: CommonDecoration.getRadius(
                      bg: '#ACEEF4'.toColor,
                      bottomLeft: 6.w,
                      bottomRight: 6.w,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        _buildDiscountPrice(),
                        if (bean.isPromotion ?? false) _buildPrice().paddingLeft(8.w),
                      ],
                    ).paddingRight(8.w),
                  ),
                ],
              ),
            ),
          ),
          if (bean.tags.notEmpty) _buildTag(),
        ],
      ),
    );
  }

  Widget _buildCoin() => IconWidget.image(Assets.pngIapCoin, width: 27.w, height: 23.w);

  Widget _buildCoinNum() => TextWidget.oneLine(
        text: (bean.exchangeCoin ?? 0).toString(),
        fontSize: 20,
        color: '#202020'.toColor,
      );

  Widget _buildDiscount() {
    double discount = bean.discount ?? 0;
    if (discount <= 0) return const SizedBox();

    return TextWidget.oneLine(text: '${discount * 100}% off', fontSize: 9, color: '#FF3EC8'.toColor);
  }

  Widget _buildDiscountPrice() => TextWidget.oneLine(
        text: '\$${bean.price ?? 0}',
        fontSize: 14,
        color: '#0F8791'.toColor,
      );

  Widget _buildPrice() =>
      TextWidget.oneLine(text: '\$${bean.originalPrice ?? 0}', fontSize: 10, color: Colors.black.withOpacity(0.3));

  Widget _buildTag() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.w),
      decoration: CommonDecoration.getRadius(
        topRight: 6.w,
        bottomLeft: 6.w,
        bg: isHot ? '#FF8FAA'.toColor : '#04A5FC'.toColor,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (isHot) _buildHotIcon().paddingRight(4.w),
          _buildTagTitle(),
        ],
      ),
    );
  }

  Widget _buildHotIcon() => IconWidget.image(Assets.pngIapHot, width: 10.w, height: 12.w);

  Widget _buildTagTitle() => TextWidget.oneLine(text: bean.tags, fontSize: 12, color: Colors.white);
}
